package com.firegod.student.service;

import com.alibaba.fastjson.JSONObject;
import com.firegod.commonutils.result.ResultCode;
import com.firegod.servicebase.dao.StudentRepository;
import com.firegod.servicebase.dao.UserRepository;
import com.firegod.servicebase.entity.Course;
import com.firegod.servicebase.entity.Student;
import com.firegod.servicebase.entity.User;
import com.firegod.servicebase.exceptionhandler.exception.GuliException;
import com.firegod.servicebase.service.BaseService;
import com.firegod.shiro.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class StudentService extends BaseService<Student, Long, StudentRepository> {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserRepository userRepository;

    public String login(String studentId, String password) {
        //判断手机号是否正确
        Student student = baseRepository.getByUserId(studentId);
        //判断对象是否为空
        student = Optional.ofNullable(student).orElseThrow(() -> GuliException.from(ResultCode.LOGIN_ERROR));

        //判断密码
        //因为存储到数据库密码肯定加密的
        //把输入的密码进行加密，再和数据密码进行比较
        //加密方式 MD5
        if (!student.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
            throw GuliException.from(ResultCode.LOGIN_ERROR);
        }

        return tokenService.createToken("Student: " + student.getUserId());

        //登录成功
        //生成token字符串，使用jwt字符串
//        return JwtUtils.getJwtToken(member.getId(), member.getNickname());
    }

    public String register(String studentId, String password) {
        //判断手机号是否正确
        User user = userRepository.getByUserId(studentId);
        //判断对象是否为空
        if (user != null) {
            throw GuliException.from(ResultCode.REDUPLICATE_STUDENT_ID_ERROR);
        }
        //判断密码
        //因为存储到数据库密码肯定加密的
        //把输入的密码进行加密，再和数据密码进行比较
        //加密方式 MD5
        Student student = new Student(studentId);
        student.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
        baseRepository.saveAndFlush(student);
        return tokenService.createToken("Student: " + student.getUserId());

        //登录成功
        //生成token字符串，使用jwt字符串
//        return JwtUtils.getJwtToken(member.getId(), member.getNickname());
    }

    public Map<String, Object> getStudentInfo() {
        HashMap<String, Object> hashMap = new HashMap<>();
        String studentId = tokenService.getCurrentUser().substring(9);
        Student student = baseRepository.getByUserId(studentId);

        if (student == null) {
            throw GuliException.from(ResultCode.STUDENT_NOT_EXIST);
        }
        hashMap.put("userId", studentId);
        hashMap.put("name", student.getName());
        hashMap.put("email", student.getEmail());
        hashMap.put("mobile", student.getMobile());
        return hashMap;
    }


    public void changePassword(String oldPassword, String password) {
        String studentId = tokenService.getCurrentUser().substring(9);
        Student student = baseRepository.getByUserId(studentId);
        if (student == null) {
            throw GuliException.from(ResultCode.STUDENT_NOT_EXIST);
        }
        if (!student.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(oldPassword.getBytes(StandardCharsets.UTF_8)))) {
            throw GuliException.from(ResultCode.PASSWORD_ERROR);
        }
        student.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
        baseRepository.saveAndFlush(student);
    }


    public void changeInfo(String mobile, String email, String name) {
        String studentId = tokenService.getCurrentUser().substring(9);
        Student student = baseRepository.getByUserId(studentId);
        if (student == null) {
            throw GuliException.from(ResultCode.STUDENT_NOT_EXIST);
        }
        if (mobile != null) {
            student.setMobile(mobile);
        }
        if (email != null) {
            student.setEmail(email);
        }
        if (name != null) {
            student.setName(name);
        }
        baseRepository.saveAndFlush(student);
    }

    public JSONObject[] getCourse() {
        String studentId = tokenService.getCurrentUser().substring(9);
        Student student = baseRepository.getByUserId(studentId);
        return student.getCourseList().stream().map(Course::show).toArray(JSONObject[]::new);
    }
}
